package com.oscar.ehome.view.loginview;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsMessage;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.igexin.sdk.PushManager;
import com.oscar.ehome.App;
import com.oscar.ehome.DemoIntentService;
import com.oscar.ehome.DiaoChaActivity;
import com.oscar.ehome.MainActivity;
import com.oscar.ehome.DemoPushService;
import com.oscar.ehome.R;
import com.oscar.ehome.WelcomeActivity;
import com.oscar.ehome.base.activity.BaseActivity;
import com.oscar.ehome.bean.loginbean.CodeBean;
import com.oscar.ehome.bean.loginbean.UserBean;
import com.oscar.ehome.bean.loginbean.logincompanyBean;
import com.oscar.ehome.bean.pagebean.DiaoChaInfo;
import com.oscar.ehome.bean.pagebean.StudyDetialBean;
import com.oscar.ehome.presenter.LoginPresenter;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.sms.SmsObserver;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.PermissionUtil;
import com.oscar.ehome.utils.util.SystemBarTintManager;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.konwledge.KnowledgeActivity;
import com.oscar.ehome.view.loginview.view.LoginView;
import com.oscar.ehome.view.pageview.FrequencyActivity;
import com.oscar.ehome.view.pageview.PdfDetialActivity;
import com.oscar.ehome.view.pageview.VideoActivity;
import com.oscar.ehome.view.setview.CheckUpdateManger;
import com.oscar.ehome.view.teamview.TeamDetailActivity;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author: MengWanhe
 * date: On 2017/6/6
 * 登录页
 */

public class LoginActivity extends BaseActivity implements LoginView, TextWatcher {

    /**
     * 手机号
     */
    @BindView(R.id.phone_edtext)
    EditText phoneEdtext;
    /**
     * 验证码
     */
    @BindView(R.id.versonnumber_edtext)
    EditText versonnumberEdtext;
    /**
     * 发送验证码
     */
    @BindView(R.id.authcode_text)
    TextView authcodeText;
    /**
     * 登录按钮
     */
    @BindView(R.id.login_buton)
    Button loginButon;
    /**
     * 客服
     */
    @BindView(R.id.tv_kefu)
    TextView tvKefu;
    /**
     * 公司名称
     */
    @BindView(R.id.campaty_text)
    TextView campatyText;
    //登录调用
    private LoginPresenter loginPresenter;
    //时间倒计时
    private TimeCount timeCount;
    String reg;
    private DiaoChaInfo diaoChaInfo;
    Pattern pattern;
    String phone = "";
    boolean isFlag = true;//是否开启了权限

    private CharSequence wordNum;//记录输入的字数
    private int selectionStart;
    private int selectionEnd;

    private CharSequence codewordNum;//记录输入的字数
    private int codeselectionStart;
    private int codeselectionEnd;
    private SmsReciver smsReciver = new SmsReciver();
    String  weiyi="1";
    /**
     * 收到短信Action
     **/
    String ACTION_SMS_RECIVER = "android.provider.Telephony.SMS_RECEIVED";
    boolean sdCardWritePermission;
    boolean phoneSatePermission;
    boolean smsSatePermission;
    UserBean userBean;
    String appToken;
    private static final int REQUEST_PERMISSION = 0;
    private StudyDetialBean wenjian;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setBaseBackground(LoginActivity.this);
        ButterKnife.bind(this);
        isPressmion();
        initView();
        loginPresenter.kefu();


        if (CommonUtils.isIndex) {
            CheckUpdate();
        }
    }

    /**
     * 初始化
     */
    public void initView() {
        loginPresenter = new LoginPresenter(this);
        phoneEdtext.addTextChangedListener(this);

        //设置phoneEdtext hint颜色
        phoneEdtext.setHintTextColor(getResources().getColor(R.color.gray_99));
        //时间
        timeCount = new TimeCount(60000, 1000);
        //判断手机号正则
        reg = "^1[3|4|5|6|7|8|9][0-9]\\d{8}$";

        pattern = Pattern.compile(reg);

        authcodeText.setEnabled(false);
        loginButon.setEnabled(false);
        TintManager.setTint(loginButon, Color.parseColor("#61C0DE"));

        versonnumberEdtext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                codewordNum = s;
                if (s.length() == 4) {
                    if (!"".equals(phoneEdtext.getText().toString())) {
                        loginButon.setEnabled(true);
                        TintManager.setTint(loginButon, Color.parseColor("#00a0e9"));
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                codeselectionStart = versonnumberEdtext.getSelectionStart();
                codeselectionEnd = versonnumberEdtext.getSelectionEnd();
                if (codewordNum.length() > 4) {
                    //删除多余输入的字（不会显示出来）
                    s.delete(codeselectionStart - 1, codeselectionEnd);
                    int tempSelection = codeselectionEnd;
                    versonnumberEdtext.setText(s);
                    versonnumberEdtext.setSelection(tempSelection);//设置光标在最后
                }
            }
        });

    }

    /**
     * 检查更新
     */
    public void CheckUpdate() {

        CheckUpdateManger manager = new CheckUpdateManger(LoginActivity.this);
        // 检查软件更新
        manager.checkUpdate();

    }

    /**
     * 检查权限
     */
    public void isPressmion() {

        PackageManager pkgManager = getPackageManager();

        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        sdCardWritePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        smsSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_SMS, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission || !smsSatePermission) {
            isFlag = false;
            requestPermission();
        } else {
            isFlag = true;
            PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        }
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS,
                        Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }

    @OnClick({R.id.authcode_text, R.id.login_buton, R.id.tv_kefu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.authcode_text://验证码
                // read phone state用于获取 imei 设备信息
                if (Build.VERSION.SDK_INT >= 23 && !smsSatePermission) {

                } else {
                    registSmsReciver();
                }

                // 忽略大小写的写法
                Matcher matcher = pattern.matcher(phoneEdtext.getText().toString());
                // 字符串是否与正则表达式相匹配
                boolean rs = matcher.matches();
                if (rs) {
                    //隐藏键盘
                    CommonUtils.hideInput(LoginActivity.this, phoneEdtext);
                    CommonUtils.hideInput(LoginActivity.this, versonnumberEdtext);
                    timeCount.start();
                    authcodeText.setTextColor(getResources().getColor(R.color.gray_99));
                    loginPresenter.recvicecode(phoneEdtext.getText().toString());
                } else {
                    Toast.makeText(getBaseContext(), getString(R.string.right_phonenumber), Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.login_buton://登录
                if (StringUtils.isEmpty(phoneEdtext.getText().toString())) {
                    ToastUtil.show(LoginActivity.this, getString(R.string.null_phonenumber));
                    break;
                }
                if (StringUtils.isEmpty(versonnumberEdtext.getText().toString())) {
                    ToastUtil.show(LoginActivity.this, getString(R.string.null_code));
                    break;
                }
                if ((versonnumberEdtext.getText().toString().length()) == 4) {
                    //隐藏键盘
                    CommonUtils.hideInput(LoginActivity.this, phoneEdtext);
                    CommonUtils.hideInput(LoginActivity.this, versonnumberEdtext);
                    //登录
                    String deviceid = "";
                    if (phoneSatePermission) {
                        deviceid = CommonUtils.getImei(LoginActivity.this);
                    }
                    boolean flags = PushManager.getInstance().isPushTurnedOn(this.getApplicationContext());
                    if (!flags) {
                        PushManager.getInstance().turnOnPush(this.getApplicationContext());
                    }
                    if (App.clientId == null) {
                        App.clientId = "";
                    }


                    loginPresenter.logins(phoneEdtext.getText().toString(), versonnumberEdtext.getText().toString(), deviceid, "android", App.clientId);
                    showLoading();
                } else {
                    ToastUtil.show(LoginActivity.this, getString(R.string.right_code));
                }
                break;
            case R.id.tv_kefu://客服
                if (phone == null || phone.equals("")) {
                    loginPresenter.kefu();
                } else {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    startActivity(intent);
                }
                break;
        }
    }

    /**
     * 登录成功
     */
    @Override
    public void navigateToHome(UserBean result) {
        userBean = result;
        dismissLoading();
        ToastUtil.show(LoginActivity.this, R.string.login_succes);
        if (result != null) {
            if (!result.equals("")) {
                if (result.getCompany().getIsNeedPay() != null && result.getCompany().getIsNeedPay().equals("0")) {
                    result.setIsPay("1");
                    String s = new Gson().toJson(result);
                    CommonUtils.dakaMap.put("s", s);
                } else {

                }
                if (MapUtils.getString(CommonUtils.dakaMap, "s") != null) {
                    SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setUserMessage(MapUtils.getString(CommonUtils.dakaMap, "s"));
                }

                //存储登录信息
                Gson gson = new Gson();
                String jsonStr = gson.toJson(result);

                SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setUserBean(jsonStr);

                 appToken = result.getAppToken();
                SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setToken(appToken);

                String status = result.getStatus();
                String name = result.getName();
                SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setUsername(name);
                String comminid = result.getId();
                SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setUuid(comminid);
                String exclusiceSrc = result.getExclusiceSrc();
                SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setExclusiceSrc(exclusiceSrc);
                String jobLevel = result.getJobLevel();
                SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setJobLevel(jobLevel);


                String color = result.getCompany().getTheme();
                if (color.equals("")) {
                    color = "#00a0e9";
                }
                SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setColor(color);

                SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().SetLogin(true);//已登录


                SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setIsMaanger(result.getIsManager());

                Intent intent;
                if (userBean.getIsManager().equals("1")) {//管理员。内勤人员
                    SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setStatus("1");
                    intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("intent", 1);
                    startActivity(intent);
                    finish();
                } else if (userBean.getIsManager().equals("2")) {
                    SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setStatus("1");
                    intent = new Intent(LoginActivity.this, KnowledgeActivity.class);
                    intent.putExtra("intent", 0);
                    startActivity(intent);
                    finish();
                } else {
                    if ("1".equals(userBean.getStatus())) {//成功
                        SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setStatus("1");
                        if (userBean.getIsPay() != null && "1".equals(userBean.getIsPay())) {

                            loginPresenter.getwelDiaochaInfo(appToken);

                        } else {
                            intent = new Intent(LoginActivity.this, MainActivity.class);
                            intent.putExtra("intent", 1);
                            startActivity(intent);
                            finish();
                        }
                    } else {//认证页面    ApproveActivity
                        if (userBean.getCompany().getIsNeedCertification() != null && userBean.getCompany().getIsNeedCertification().equals("0")) {
                            SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setStatus("1");
                            intent = new Intent(LoginActivity.this, MainActivity.class);
                            intent.putExtra("intent", 1);
                            startActivity(intent);
                            finish();
                        } else {
                            SystemConfigFactory.getInstance(LoginActivity.this).getSystemConfig().setStatus(userBean.getStatus());
                            intent = new Intent(LoginActivity.this, ApproveActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                }
            }
        }
    }

    @Override
    public void getDiaocharesult(DiaoChaInfo result) {

        diaoChaInfo = result;
        Intent intent;
        if (diaoChaInfo != null && !diaoChaInfo.equals("")) {
            intent = new Intent(LoginActivity.this, DiaoChaActivity.class);
            startActivity(intent);
            LoginActivity.this.overridePendingTransition(R.anim.activity_open, R.anim.jingzi);
            finish();
        } else {
           loginPresenter.getwenjianInfo(appToken);

        }


    }

    @Override
    public void getbaojianjufile(StudyDetialBean result) {
        Log.e("cacacaee", "getbaojianjufile: "+result );
        wenjian = result;
        Intent intent;
        if (wenjian != null && !wenjian.equals("")) {
            String learnType = wenjian.getLearnType();
            if ("video/mp4".equals(learnType)) {//视频
                intent = new Intent(LoginActivity.this, VideoActivity.class);
                intent.putExtra("id", wenjian.getId());
                intent.putExtra("type", "qiangzhi");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                LoginActivity.this.startActivity(intent);
                LoginActivity.this.overridePendingTransition(R.anim.activity_open, R.anim.jingzi);
                LoginActivity.this.finish();
            } else if ("application/pdf".equals(learnType)) {//PDF
                intent = new Intent(LoginActivity.this, PdfDetialActivity.class);
                intent.putExtra("id", wenjian.getId());
                intent.putExtra("type", "qiangzhi");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                LoginActivity.this.startActivity(intent);
                LoginActivity.this.overridePendingTransition(R.anim.activity_open, R.anim.jingzi);
                LoginActivity.this.finish();
            } else if ("audio/mp3".equals(learnType)) {//音频
                intent = new Intent(LoginActivity.this, FrequencyActivity.class);
                intent.putExtra("id", wenjian.getId());
                intent.putExtra("type", "qiangzhi");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                LoginActivity.this.startActivity(intent);
                LoginActivity.this.overridePendingTransition(R.anim.activity_open, R.anim.jingzi);
                LoginActivity.this.finish();
            }

        } else {
            intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.putExtra("intent", 1);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 验证码
     *
     * @param result
     */
    @Override
    public void code(logincompanyBean result) {
        if (result != null) {
            if (!result.equals(""))
                campatyText.setVisibility(View.VISIBLE);
            campatyText.setText(result.getName());
            Toast.makeText(LoginActivity.this, getString(R.string.success_code), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 客服电话
     *
     * @param result
     */
    @Override
    public void phoneNumber(CodeBean result) {
        if (result != null) {
            if (!result.equals(""))
                phone = result.getPhone();
        }
    }

    /**
     * 登录失败
     */
    @Override
    public void erroy() {
        dismissLoading();
        ToastUtil.show(LoginActivity.this, getString(R.string.erry));

    }

    @Override
    public void erry(String result) {
        dismissLoading();

        if(result.equals("手机号不存在，请先注册！")){
            new AlertDialog.Builder(this).setTitle("提示").setMessage("手机号未注册，请先进行注册")

                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which){
                            dialog.dismiss();

                        }
                    }).show();

        }else{
            if (result.equals("tiaoguowenjuandiaocha")&&weiyi.equals("1")) {
                weiyi="2";
                Intent intent;
                if (wenjian != null && !wenjian.equals("")) {
                    String learnType = wenjian.getLearnType();

                    if ("video/mp4".equals(learnType)) {//视频
                        intent = new Intent(LoginActivity.this, VideoActivity.class);
                        intent.putExtra("id", wenjian.getId());
                        intent.putExtra("type", "qiangzhi");
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        LoginActivity.this.startActivity(intent);
                        LoginActivity.this.overridePendingTransition(R.anim.activity_open, R.anim.jingzi);
                        LoginActivity.this.finish();
                    } else if ("application/pdf".equals(learnType)) {//PDF
                        intent = new Intent(LoginActivity.this, PdfDetialActivity.class);
                        intent.putExtra("id", wenjian.getId());
                        intent.putExtra("type", "qiangzhi");
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        LoginActivity.this.startActivity(intent);
                        LoginActivity.this.overridePendingTransition(R.anim.activity_open, R.anim.jingzi);
                        LoginActivity.this.finish();
                    } else if ("audio/mp3".equals(learnType)) {//音频
                        intent = new Intent(LoginActivity.this, FrequencyActivity.class);
                        intent.putExtra("id", wenjian.getId());
                        intent.putExtra("type", "qiangzhi");
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        LoginActivity.this.startActivity(intent);
                        LoginActivity.this.overridePendingTransition(R.anim.activity_open, R.anim.jingzi);
                        LoginActivity.this.finish();
                    }

                } else {
                    intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("intent", 1);
                    startActivity(intent);
                    finish();
                }


            } else if(result.equals("tiaoguowenjuan")&&weiyi.equals("1")){
                weiyi="2";
                Intent intent;
                if (diaoChaInfo != null && !diaoChaInfo.equals("")) {
                    intent = new Intent(LoginActivity.this, DiaoChaActivity.class);
                    startActivity(intent);
                    LoginActivity.this.overridePendingTransition(R.anim.activity_open, R.anim.jingzi);
                    finish();

                } else {
                    intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("intent", 1);
                    startActivity(intent);
                    finish();
                }

            }else{
                Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show();
            }
        }





    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        wordNum = s;
        if (s.length() == 11) {
            // 忽略大小写的写法
            Matcher matcher = pattern.matcher(phoneEdtext.getText().toString());
            // 字符串是否与正则表达式相匹配
            boolean rs = matcher.matches();
            if (rs) {
                authcodeText.setTextColor(getResources().getColor(R.color.bg));
                authcodeText.setEnabled(true);
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        selectionStart = phoneEdtext.getSelectionStart();
        selectionEnd = phoneEdtext.getSelectionEnd();

        if (wordNum.length() > 11) {
            //删除多余输入的字（不会显示出来）
            s.delete(selectionStart - 1, selectionEnd);
            int tempSelection = selectionEnd;
            phoneEdtext.setText(s);
            phoneEdtext.setSelection(tempSelection);//设置光标在最后
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
            } else {
                PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 倒计时
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {//计时完毕时触发
            authcodeText.setText("重新验证");
            authcodeText.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            authcodeText.setClickable(false);
            authcodeText.setText(millisUntilFinished / 1000 + "秒");
        }
    }

    /**
     * 设置系统标题背景颜色
     *
     * @param act
     */
    public void setBaseBackground(Activity act) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            CommonUtils.setTranslucentStatus(true, act);
            SystemBarTintManager tintManager = new SystemBarTintManager(act);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.white);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        try {
            for (Activity activity : CommonUtils.activitymap) {
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

    private void registSmsReciver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_SMS_RECIVER);
        // 设置优先级 不然监听不到短信
        filter.setPriority(1000);
        registerReceiver(smsReciver, filter);
    }

    /**
     * 短信广播接受者 用户监听短信，自动填写验证码
     */
    private class SmsReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Object[] objs = (Object[]) intent.getExtras().get("pdus");
            for (Object obj : objs) {
                byte[] pdu = (byte[]) obj;
                SmsMessage sms = SmsMessage.createFromPdu(pdu);
                // 短信的内容
                String message = sms.getMessageBody();
                Log.d("log", "message     " + message);
                // 短息的手机号，如果你们公司发送验证码的号码是固定的这里可以进行一个号码的校验
                String from = sms.getOriginatingAddress();
                Log.d("log", "from     " + from);
                analysisVerify(message);

            }
        }

    }

    /**
     * 解析短信并且回写  这里解析的是纯数字的短信，如果小伙伴的验证码包含字母的话，可用正则替换
     *
     * @param message
     */
    private void analysisVerify(String message) {
        char[] msgs = message.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < msgs.length; i++) {
            if ('0' <= msgs[i] && msgs[i] <= '9') {
                sb.append(msgs[i]);
            }
        }

        versonnumberEdtext.setText(sb.toString());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消短信广播注册
//        if (smsReciver != null) {
//            unregisterReceiver(smsReciver);
//            smsReciver = null;
//        }
    }
}
